package com.example.demo_debezium_pgsql.util;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Configuration
@ConfigurationProperties(prefix = "spring.datasource")
public class PgProperties implements InitializingBean {

    private String driverClassName;
    private String url;
    private String username;
    private String password;

    private String host;
    private int port;
    private String dbName;
    private String currentSchema;

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getHost() {
        return host;
    }

    public Integer getPort() {
        return port;
    }

    public String getDbName() {
        return dbName;
    }

    public String getCurrentSchema() {
        return currentSchema;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        String reg = "jdbc:postgresql://([a_zA_Z\\d.]*):(\\d{2,5})/(\\w*)\\??(\\w*=\\w*)?(&\\w*=\\w*)*";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(this.url);
        if(matcher.find()){
            int count = matcher.groupCount();
            this.host = matcher.group(1);
            this.port = Integer.valueOf(matcher.group(2));
            this.dbName = matcher.group(3);
            for (int i = 4; i <= count; i++) {
                String group = matcher.group(i);
                if(group.startsWith("currentSchema=") || group.startsWith("&currentSchema=") ){
                    this.currentSchema = group.substring(group.indexOf("="));
                    break;
                }
            }
        }
    }
}
